package com.iflytek.aidemo.teacher;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ImageView;
import android.util.LruCache;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.graphics.Typeface;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.iflytek.aidemo.R;
import com.iflytek.aidemo.api.ApiService;
import com.iflytek.aidemo.api.ApiServiceImpl;
import com.iflytek.aidemo.model.ApiResponse;
import com.iflytek.aidemo.model.ImageRecord;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * 学生成绩详情页：展示该学生最近一次的成绩和所有题目详情（此处用模拟数据）。
 */
public class StudentScoreDetailActivity extends AppCompatActivity {

    private TextView tvHeader;
    private RecyclerView rvDetails;
    private final List<RecordItem> records = new ArrayList<>();
    private RecordAdapter adapter;
    private final ExecutorService imagePool = Executors.newFixedThreadPool(3);
    // 内存图片缓存：提升二次显示速度，减少延迟
    private LruCache<String, Bitmap> imageCache;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_score_detail);

        View back = findViewById(R.id.btn_back);
        if (back != null) back.setOnClickListener(v -> finish());

        tvHeader = findViewById(R.id.tv_header);
        rvDetails = findViewById(R.id.rv_details);

        int studentId = getIntent().getIntExtra("student_id", -1);
        String studentName = getIntent().getStringExtra("student_name");
        if (studentName == null) studentName = "学生" + studentId;

        tvHeader.setText(studentName + " 的成绩详情");

        rvDetails.setLayoutManager(new LinearLayoutManager(this));
        adapter = new RecordAdapter(records);
        rvDetails.setAdapter(adapter);

        // 初始化图片缓存（使用最大可用内存的 1/8）
        final int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024);
        final int cacheSize = maxMem / 8; // KB
        imageCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024; // KB
            }
        };

        String date = getIntent().getStringExtra("date");
        loadStudentDetail(studentId, date);
    }

    // 构建突出颜色与加粗样式的“错题/总数”文本
    private CharSequence buildCountStyledText(int wrong, int total) {
        String label = "错题/总数 ";
        String content = label + wrong + "/" + total;
        SpannableString ss = new SpannableString(content);
        // 加粗“错题/总数”标签
        ss.setSpan(new StyleSpan(Typeface.BOLD), 0, label.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 错题数字胶囊背景（红底白字）
        int startWrong = label.length();
        int endWrong = startWrong + String.valueOf(wrong).length();
        int padH = (int)(getResources().getDisplayMetrics().density * 6); // 左右内边距
        int padV = (int)(getResources().getDisplayMetrics().density * 2); // 上下内边距
        float radius = getResources().getDisplayMetrics().density * 10;
        ss.setSpan(new RoundedBackgroundSpan(0xFFE53935, 0xFFFFFFFF, radius, padH, padV), startWrong, endWrong, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 其余保持深灰（可选：为“/总数”加深色）
        return ss;
    }

    // 自定义胶囊背景 Span：绘制圆角矩形背景和前景色文本
    private static class RoundedBackgroundSpan extends android.text.style.ReplacementSpan {
        private final int bgColor;
        private final int fgColor;
        private final float radius;
        private final int paddingH;
        private final int paddingV;

        RoundedBackgroundSpan(int bgColor, int fgColor, float radius, int paddingH, int paddingV) {
            this.bgColor = bgColor;
            this.fgColor = fgColor;
            this.radius = radius;
            this.paddingH = paddingH;
            this.paddingV = paddingV;
        }

        @Override
        public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
            float textWidth = paint.measureText(text, start, end);
            return (int) Math.ceil(textWidth + paddingH * 2);
        }

        @Override
        public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
            float textWidth = paint.measureText(text, start, end);
            Paint.FontMetrics fm = paint.getFontMetrics();
            float textHeight = fm.descent - fm.ascent;
            float rectLeft = x;
            // 基于 baseline 计算背景矩形垂直位置
            float rectTop = y + fm.ascent - paddingV;
            float rectRight = x + textWidth + paddingH * 2;
            float rectBottom = y + fm.descent + paddingV;

            int oldColor = paint.getColor();
            Paint.Style oldStyle = paint.getStyle();

            // 背景
            paint.setColor(bgColor);
            paint.setStyle(Paint.Style.FILL);
            RectF rect = new RectF(rectLeft, rectTop, rectRight, rectBottom);
            canvas.drawRoundRect(rect, radius, radius, paint);

            // 文本（居中显示，x向右偏移 paddingH）
            paint.setColor(fgColor);
            canvas.drawText(text, start, end, x + paddingH, y, paint);

            // 还原
            paint.setColor(oldColor);
            paint.setStyle(oldStyle);
        }
    }

    private final ApiService api = new ApiServiceImpl();

    private void loadStudentDetail(int studentId, String date) {
        new Thread(() -> {
            ApiResponse<List<ImageRecord>> resp = api.getStudentScoreDetail(studentId, date);
            final List<RecordItem> list = new ArrayList<>();
            if (resp != null && resp.getCode() == 200 && resp.getData() != null) {
                for (ImageRecord ir : resp.getData()) {
                    if (ir == null) continue;
                    RecordItem item = new RecordItem();
                    item.imageUrl = normalizeUrl(ir.getRecordImagePath());
                    item.count = ir.getCount() == null ? 0 : ir.getCount();
                    item.countCorrect = ir.getCountCorrect() == null ? 0 : ir.getCountCorrect();
                    item.submitTime = ir.getSubmitTime();
                    list.add(item);
                }
            }
            runOnUiThread(() -> {
                records.clear();
                records.addAll(list);
                adapter.notifyDataSetChanged();
            });
        }).start();
    }

    // 记录数据结构
    static class RecordItem {
        String imageUrl;
        int count;
        int countCorrect;
        String submitTime;
        String studentName;
    }

    // 适配器：图片 + 错题/总数角标 + 时间，卡片样式，条目间距
    class RecordAdapter extends RecyclerView.Adapter<RecordAdapter.VH> {
        private final List<RecordItem> data;
        RecordAdapter(List<RecordItem> data) { this.data = data; }
        class VH extends RecyclerView.ViewHolder {
            ImageView image;
            TextView tvCount; // 错题/总数，显示在图片下方
            TextView tvTime;  // 提交时间
            VH(View itemView) {
                super(itemView);
                android.view.ViewGroup root = (android.view.ViewGroup) itemView;
                android.widget.FrameLayout imageBox = (android.widget.FrameLayout) root.getChildAt(0);
                image = (ImageView) imageBox.getChildAt(0);
                tvCount = (TextView) root.getChildAt(1);
                tvTime = (TextView) root.getChildAt(2);
            }
        }
        @Override public VH onCreateViewHolder(android.view.ViewGroup parent, int viewType) {
            // 卡片容器
            android.widget.LinearLayout root = new android.widget.LinearLayout(parent.getContext());
            root.setOrientation(android.widget.LinearLayout.VERTICAL);
            int pad = (int) (parent.getResources().getDisplayMetrics().density * 12);
            android.widget.LinearLayout.LayoutParams lp = new android.widget.LinearLayout.LayoutParams(
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                    android.view.ViewGroup.LayoutParams.WRAP_CONTENT
            );
            lp.setMargins(pad, pad, pad, pad); // 条目间距
            root.setLayoutParams(lp);

            // 圆角背景
            android.graphics.drawable.GradientDrawable bg = new android.graphics.drawable.GradientDrawable();
            bg.setColor(0xFFFFFFFF);
            float radius = parent.getResources().getDisplayMetrics().density * 8;
            bg.setCornerRadius(radius);
            bg.setStroke((int)(parent.getResources().getDisplayMetrics().density * 0.5f), 0x11000000);
            root.setBackground(bg);
            root.setPadding(pad, pad, pad, pad);

            // 图片区域：FrameLayout（不再显示角标）
            android.widget.FrameLayout imageBox = new android.widget.FrameLayout(parent.getContext());
            android.widget.LinearLayout.LayoutParams boxLp = new android.widget.LinearLayout.LayoutParams(
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                    (int) (parent.getResources().getDisplayMetrics().density * 240)
            );
            imageBox.setLayoutParams(boxLp);

            ImageView iv = new ImageView(parent.getContext());
            iv.setScaleType(ImageView.ScaleType.FIT_CENTER); // 显示完整，不裁剪
            iv.setAdjustViewBounds(true);
            iv.setLayoutParams(new android.widget.FrameLayout.LayoutParams(
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                    android.view.ViewGroup.LayoutParams.MATCH_PARENT
            ));
            imageBox.addView(iv);

            root.addView(imageBox);

            // 错题/总数
            TextView tvCount = new TextView(parent.getContext());
            tvCount.setTextSize(14);
            tvCount.setTextColor(0xFF333333);
            tvCount.setPadding(0, pad / 2, 0, 0);
            root.addView(tvCount);

            // 提交时间
            TextView tvT = new TextView(parent.getContext());
            tvT.setTextSize(12);
            tvT.setTextColor(0xFF666666);
            tvT.setPadding(0, (int)(pad * 0.25f), 0, 0);
            root.addView(tvT);

            return new VH(root);
        }
        @Override public void onBindViewHolder(VH holder, int position) {
            RecordItem item = data.get(position);
            int wrong = Math.max(0, item.count - item.countCorrect);
            holder.tvCount.setText(buildCountStyledText(wrong, item.count));
            holder.tvTime.setText("提交时间：" + (item.submitTime == null ? "" : item.submitTime));
            String u = normalizeUrl(item.imageUrl);
            holder.image.setTag(u);
            // 先从缓存取，命中则立显
            Bitmap cached = imageCache.get(u);
            if (cached != null && !cached.isRecycled()) {
                holder.image.setImageBitmap(cached);
                return;
            }
            holder.image.setImageDrawable(null); // 未命中则清空等待加载
            // 加载图片
            imagePool.execute(() -> {
                Bitmap bmp = null;
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(u).openConnection();
                    conn.setConnectTimeout(8000);
                    conn.setReadTimeout(8000);
                    conn.setInstanceFollowRedirects(true);
                    conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Android) StudentScoreDetail/1.0");
                    conn.setDoInput(true);
                    try (java.io.InputStream is = conn.getInputStream()) {
                        bmp = BitmapFactory.decodeStream(is);
                    }
                } catch (Exception ignored) {}
                final Bitmap fb = bmp;
                runOnUiThread(() -> {
                    Object tag = holder.image.getTag();
                    if (tag != null && tag.equals(u)) {
                        if (fb != null) {
                            imageCache.put(u, fb);
                            holder.image.setImageBitmap(fb);
                        } else {
                            holder.image.setImageDrawable(null);
                        }
                    }
                });
            });
        }
        @Override public int getItemCount() { return data == null ? 0 : data.size(); }
    }

    // 规范化图片URL
    private String normalizeUrl(String raw) {
        if (raw == null) return "";
        String url = raw.trim();
        if (url.isEmpty()) return url;
        url = url.replace("aliyuncs.comapp/", "aliyuncs.com/app/");
        // 若以 // 开头，补充 https:
        if (url.startsWith("//")) url = "https:" + url;
        // 若没有协议，且以域名开头，默认 https
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            // 粗略判断可能是域名或路径
            if (url.matches("^[A-Za-z0-9.-]+/.*")) {
                url = "https://" + url;
            }
        }
        // 若出现 .com后紧跟字母而非/，尝试在 .com 后插入/
        url = url.replace(".comapp/", ".com/app/");
        url = url.replace(".cnapp/", ".cn/app/");
        return url;
    }
}
